package cn.tedu.qxhouserent.house.service.impl;

import cn.tedu.qxhouserent.commons.ex.ServiceException;
import cn.tedu.qxhouserent.commons.web.ServiceCode;
import cn.tedu.qxhouserent.house.mapper.*;
import cn.tedu.qxhouserent.house.pojo.entity.*;
import cn.tedu.qxhouserent.house.pojo.param.UserHouseCollectionAddNewParam;
import cn.tedu.qxhouserent.house.pojo.param.UserNewsCollectionAddNewParam;
import cn.tedu.qxhouserent.house.pojo.vo.NewsDetailStandardVO;
import cn.tedu.qxhouserent.house.service.UserHouseCollectionService;
import cn.tedu.qxhouserent.house.service.UserNewsCollectionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static cn.tedu.qxhouserent.commons.web.ServiceCode.*;

@Service
@Slf4j
public class UserNewsCollectionImpl implements UserNewsCollectionService {

    @Autowired
    private UserNewsCollectionMapper userNewsCollectionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NewsDetailMapper newsDetailMapper;



    @Override
    public void addNew(UserNewsCollectionAddNewParam userNewsCollectionAddNewParam) {
        log.debug("开始处理【用户添加资讯收藏】的业务，参数：{}", userNewsCollectionAddNewParam);
        // 检查该用户是否已收藏此资讯,如果已收藏,则抛出异常
        QueryWrapper<UserNewsCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userNewsCollectionAddNewParam.getUserId())
                .eq("news_detail_id",userNewsCollectionAddNewParam.getNewsDetailId());
        Integer countByUserIdAndNewsDetailId = userNewsCollectionMapper.selectCount(queryWrapper);
        log.debug("根据用户id和资讯id统计匹配的收藏数量，结果：{}", countByUserIdAndNewsDetailId);
        if (countByUserIdAndNewsDetailId > 0){
            String message = "添加收藏失败,该资讯已经被收藏!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        // 检查该用户是否存在,如果不存在,则抛出异常
        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id",userNewsCollectionAddNewParam.getUserId());
        Integer countByUserId = userMapper.selectCount(queryWrapper2);
        log.debug("根据用户id统计匹配的用户数量，结果：{}", countByUserId);
        if (countByUserId == 0){
            String message = "添加收藏失败,用户不存在!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        // 检查该资讯是否存在,如果不存在,则抛出异常
        QueryWrapper<NewsDetail> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("id",userNewsCollectionAddNewParam.getNewsDetailId());
        Integer countByNewsDetailId = newsDetailMapper.selectCount(queryWrapper3);
        log.debug("根据资讯id统计匹配的资讯数量，结果：{}", countByNewsDetailId);
        if (countByNewsDetailId == 0){
            String message = "添加收藏失败,资讯不存在!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        //写入关联表
        UserNewsCollection userNewsCollection = new UserNewsCollection();
        BeanUtils.copyProperties(userNewsCollectionAddNewParam,userNewsCollection);
        userNewsCollection.setGmtCollection(LocalDateTime.now());
        log.debug("准备将新的收藏数据写入到数据库，数据：{}", userNewsCollection);
        int rows = userNewsCollectionMapper.insert(userNewsCollection);
        if (rows != 1){
            String message = "添加收藏失败,服务器正忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ERR_INSERT,message);
        }

        //增加收藏数
        NewsDetailStandardVO standardById = newsDetailMapper.getStandardById(userNewsCollectionAddNewParam.getNewsDetailId());
        if (standardById.getCollectionCount() == null) {
            String message = "数据库数据错误！";
            log.debug(message);
            throw new ServiceException(ERR_UPLOAD_INVALID_TYPE, message);
        }
        standardById.setCollectionCount(standardById.getCollectionCount() + 1L);
        NewsDetail newsDetail = new NewsDetail();
        BeanUtils.copyProperties(standardById, newsDetail);
        newsDetail.setGmtModified(LocalDateTime.now());
        int i = newsDetailMapper.updateById(newsDetail);
        if (i != 1){
            String message = "修改收藏数失败,服务器正忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ERR_UPDATE,message);
        }
        log.debug("将新的收藏数据写入到数据库，完成！");


    }

    @Override
    public void deleteByUserId(Long userId, Long newsDetailId) {
        log.debug("开始处理【通过用户id和资讯id删除收藏】的业务，用户id：{},资讯id: {}" ,userId,newsDetailId);

        // 根据用户id和资讯id检查收藏是否存在，如果不存在，则抛出异常
        QueryWrapper<UserNewsCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("news_detail_id",newsDetailId);
        int countById = userNewsCollectionMapper.selectCount(queryWrapper);
        log.debug("根据用户id和资讯id统计匹配的收藏数量，结果：{}" , countById);
        if (countById==0){
            String message = "删除收藏失败，收藏数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        int rows = userNewsCollectionMapper.deleteByUserIdAndNewsDetailId(userId, newsDetailId);
        if (rows < 1){
            String message = "删除收藏失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ERR_DELETE, message);
        }

        //减少收藏数
        NewsDetailStandardVO standardById = newsDetailMapper.getStandardById(newsDetailId);
        if (standardById.getCollectionCount() == null) {
            String message = "数据库数据错误！";
            log.debug(message);
            throw new ServiceException(ERR_UPLOAD_INVALID_TYPE, message);
        }
        standardById.setCollectionCount(standardById.getCollectionCount() - 1L);
        NewsDetail newsDetail = new NewsDetail();
        BeanUtils.copyProperties(standardById, newsDetail);
        newsDetail.setGmtModified(LocalDateTime.now());
        int i = newsDetailMapper.updateById(newsDetail);
        if (i != 1){
            String message = "修改收藏数失败,服务器正忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ERR_UPDATE,message);
        }
        log.debug("将收藏数据从数据库中删除，完成！");
    }

    @Override
    public boolean newsCollectionInfo(Long id, Long newsId) {
        log.debug("开始处理【判断用户是否收藏此资讯】的业务,用户id: {}, 页码:{}", id, newsId);
        QueryWrapper<UserNewsCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id).eq("news_detail_id", newsId);
        Integer integer = userNewsCollectionMapper.selectCount(queryWrapper);
        log.debug("处理【判断用户是否收藏此资讯】的业务完毕！");
        if (integer != 0) {
            return true;
        }
        return false;
    }
}
